#include "rtc_isr.h"

void rtc_isr(void)
{
	Byte cause = read_rtc(RTC_STAT_C);
	
	if(cause & RTC_PF) // periodic interrupt
	{
		switch(state)
		{
			case INACTIVE:
				break;

			case STOPPED:
				if(!isEmptyGQueue(music_queue))
				{
					Note* nt = (Note*)getGQueue(music_queue);
					if(nt->freq != PAUSE_FREQ)
					{
						timer_load(TIMER_2, get_divider(notes_frequency[nt->freq]));
						speaker_on();
					}
					ms_count = nt->dur;
					state = PLAY;
				}
				break;
				
			case PLAY:
				if(ms_count-- == 0)
				{
					speaker_off();
					//ms_count = 20;
					ms_count = bgm->pause;
					state = PAUSE;
					if(song_ind < bgm->lenght)
						putGQueue(music_queue, &(bgm->notes[song_ind++]));
					else if(song_loop)
					{
						song_ind = 0;
						putGQueue(music_queue, &(bgm->notes[song_ind++]));
					}
				}
				break;
				
			case PAUSE:
				if(ms_count-- == 0)
					state = STOPPED;
				break;
		}
	}
	
	outportb(PIC1_CMD, EOI);
	outportb(PIC2_CMD, EOI);
}
